package org.garbagecan.dwrstudy;

import org.directwebremoting.*;

import javax.servlet.http.HttpSession;
import java.util.*;

public class ActiveReverseAjaxUtils {

	private static ActiveReverseAjaxUtils utils = new ActiveReverseAjaxUtils();

	Map<String, ScriptSession> map = new LinkedHashMap<String, ScriptSession>();

	Map<String, Integer> mapTimeoutCount = new LinkedHashMap<String, Integer>();

	private ActiveReverseAjaxUtils() {

	}

	public static ActiveReverseAjaxUtils getInstance() {
		return utils;
	}

	public void start() {
		new Thread(new Runnable() {
			public void run() {
				while(true) {
					try {
						Thread.sleep(2000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}

					for (String sessionId : map.keySet()) {
						ScriptSession scriptSession = map.get(sessionId);

						String message = "";
						if (mapTimeoutCount.get(sessionId) >= 10) {
							message += "Session: " + sessionId + " Time Out";
						} else {
							message += "Session: " + sessionId + ", ";
							message += "Time: " + Calendar.getInstance().getTime();
						}

						ScriptBuffer scriptBuffer = new ScriptBuffer();
						scriptBuffer.appendScript("showMessage(").appendData(message).appendScript(");");

						scriptSession.addScript(scriptBuffer);

						mapTimeoutCount.put(sessionId, mapTimeoutCount.get(sessionId) + 1);
					}
				}
			}
		}).start();
	}

	public void register(HttpSession session, ScriptSession scriptSession) {
		scriptSession.setAttribute("SESSION", session);
		map.put(session.getId(), scriptSession);
		mapTimeoutCount.put(session.getId(), 0);
	}
}
